package app.repositories.impl;

import java.util.List;

import javax.persistence.EntityManager;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.util.StringUtils;

import app.models.FluxoCaixa;
import app.models.enums.TipoFluxoCaixa;
import app.repositories.FluxoCaixaRepository;
import app.repositories.Repository;
import app.util.Constants;
import br.com.caelum.vraptor.ioc.Component;

@Component
public class FluxoCaixaRepositoryImpl extends Repository<FluxoCaixa, Long> implements FluxoCaixaRepository {

	protected FluxoCaixaRepositoryImpl(EntityManager entityManager) {
		super(entityManager);
	}
	
	@SuppressWarnings("unchecked")
	public List<FluxoCaixa> findByPeriodAndByType(String dataInicial, String dataFinal, TipoFluxoCaixa type) {
		Criteria criteria = createCriteria();
		
		criteria.add(Restrictions.between(Constants.DATA_CADASTRO, dataInicial, dataFinal));
		
		if(type != null){
			criteria.add(Restrictions.eq(Constants.TIPO_FLUXO_CAIXA, type));
		}
		
		return criteria.list();
	}
	
	@SuppressWarnings("unchecked")
	public List<FluxoCaixa> findByFilter(String filter) {
		Criteria criteria = createCriteria();
		
		if (StringUtils.hasLength(filter)) {
			criteria.add(Restrictions.ilike(Constants.DESCRICAO, filter, MatchMode.ANYWHERE));
			criteria.addOrder(Order.asc(Constants.DESCRICAO));
		}
		
		return criteria.list();
	}
	
	@SuppressWarnings("unchecked")
	public List<FluxoCaixa> findAllOrdered() {
		Criteria criteria = createCriteria();
		
		criteria.addOrder(Order.asc(Constants.DESCRICAO));
		criteria.setMaxResults(10);
		
		return criteria.list();
	}
	
	@SuppressWarnings("unchecked")
	public List<FluxoCaixa> findLastCreditos() {
		Criteria criteria = createCriteria();
		
		criteria.addOrder(Order.desc(Constants.DATA_CADASTRO));
		criteria.addOrder(Order.desc(Constants.HORA_CADASTRO));
		criteria.setMaxResults(10);
		
		return criteria.list();
	}
}
